<template>
  <div class="about">
    <div class="data_from">
      <div>
        <span class="bold">站号: </span>
        <el-select v-model="station" placeholder="请选择" clearable>
          <el-option
            v-for="item in dataList"
            :key="item.站号"
            :label="item.站名"
            :value="item.站号"
          >
          </el-option>
        </el-select>
      </div>
      <div>
        <span class="bold" style="margin-left: 15px">日期: </span>
        <el-date-picker
        v-model="date"
        type="datetimerange"
        value-format="YYYY-MM-DD HH:mm:ss"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
      >
      </el-date-picker>
      </div>
      <div style="margin-left: 15px">
        <el-button type="primary" @click="queryList">查询</el-button>
      </div>
    </div>
    <div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="消费明细" name="消费明细">
          <vxe-toolbar ref="toolbarRef" print>
              <template #buttons>
                <vxe-button content="打印表格" @click="printEvent" :loading="printLoading"></vxe-button>
                <vxe-button content="表格导出" @click="onExport" :loading="loading"></vxe-button>
              </template>
            </vxe-toolbar>
            <vxe-table
              :data="客户消费明细List"
              :loading="loading"
              ref="tableRef">
              <vxe-column field="卡号" title="卡号"></vxe-column>
              <vxe-column field="日期" title="日期"></vxe-column>
              <vxe-column field="油品名" title="油品名"></vxe-column>
              <vxe-column field="油品号" title="油品号"></vxe-column>
              <vxe-column field="车牌号" title="车牌号"></vxe-column>
              <vxe-column field="数量" title="数量"></vxe-column>
              <vxe-column field="单价金额" title="单价金额"></vxe-column>
              <vxe-column field="结算金额" title="结算金额"></vxe-column>
            </vxe-table>
          <vxe-pager
                :current-page="queryForm.currentPage"
                :page-size="queryForm.pageSize"
                :total="totalResult"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                @page-change="getData">
          </vxe-pager>
        </el-tab-pane>
        <!-- 充值明细 -->
        <el-tab-pane label="充值明细" name="充值明细">
          <vxe-toolbar ref="toolbarRef" print>
              <template #buttons>
                <vxe-button content="打印表格" @click="printEvent" :loading="printLoading"></vxe-button>
                <vxe-button content="表格导出" @click="onExport" :loading="loading"></vxe-button>
              </template>
            </vxe-toolbar>
            <vxe-table
            :data="客户充值明细List"
            :loading="loading"
            ref="tableRef">
            <vxe-column field="卡号" title="卡号"></vxe-column>
            <vxe-column field="名称" title="名称"></vxe-column>
            <vxe-column field="充值时间" title="充值时间"></vxe-column>
            <vxe-column field="充值金额" title="充值金额"></vxe-column>
            <vxe-column field="支付类型" title="支付类型"></vxe-column>
          </vxe-table>
          <vxe-pager
                :current-page="queryForm1.currentPage"
                :page-size="queryForm1.pageSize"
                :total="totalResult1"
                :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
                @page-change="getData">
          </vxe-pager>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import http from '../api/http'
import { ElMessage } from 'element-plus'
import moment from 'moment'
import { useRouter } from 'vue-router'

const router = useRouter()
const activeName = ref('消费明细') // tabs 
const dataList = ref([]) // 站点下拉数量
const date = ref() // 日期
const station = ref() // 站号
const tableRef = ref()
const loading = ref(true)
const totalResult = ref(0) // 总条数
const printLoading = ref(false)

const 客户消费明细List = ref([]) 
const 客户消费明细全部数据List = ref([])
const queryForm = ref({
  currentPage: 1,
  pageSize: 10
})

const print = ref({
  currentPage: 0,
  pageSize: 0
})
const print1 = ref({
  currentPage: 0,
  pageSize: 0
})

const totalResult1 = ref(0) // 总条数
const 客户充值明细List = ref([]) 
const 客户充值明细全部数据List = ref([])
const queryForm1 = ref({
  currentPage: 1,
  pageSize: 10
})


// 获取站点
function getQueryStation() {
  http.get('/common/queryStation').then(res => {
    if (res.data.status === 0) {
      dataList.value = res.data.data
    } else {
      ElMessage.error(res.data.msg)
      router.push('/login')
    }
  }).catch(error => {
    console.log(error)
  })
}
// tabs 
function handleClick(tab, event) {
  activeName.value = tab.props.label
  // 处理重复请求
  if (activeName.value === '消费明细') {
    if (客户消费明细全部数据List.value.length > 0) {
      return 
    }
  } else {
    if (客户充值明细全部数据List.value.length > 0) {
      return 
    }
  }
  queryList()
}
// 查询
function queryList() {
  if (!date.value) {
    ElMessage.warning('请选择日期')
    return
  }
  loading.value = true
  const data = {
    startTime: date.value[0],
    endTime: date.value[1],
    station: station.value
  }
    if (activeName.value === '消费明细') {
      http.post('/client/consumeDetail', data).then(res => {
        loading.value = false
        totalResult.value = res.data.rows
        客户消费明细全部数据List.value = res.data.data
        handlePageChange(queryForm.value.currentPage, queryForm.value.pageSize)
      }).catch(error => {
        loading.value = false
        ElMessage.error(error)
      })
    }
    else {
      http.post('/client/rechangeRecord', data).then(res => {
        loading.value = false
        totalResult1.value = res.data.rows
        客户充值明细全部数据List.value = res.data.data
        handlePageChange(queryForm1.value.currentPage, queryForm1.value.pageSize)
        }).catch(error => {
          loading.value = false
        ElMessage.error(error)
        })
    }
}
// 打印
const printEvent = () => {
  if (activeName.value === '消费明细') {
    if (totalResult.value > 3000) {
      ElMessage.warning('由于性能原因，不支持超过3000条的数据打印, 请导出为文件后再打印!')
      return false
    }
    printLoading.value = true
    handlePageChange(1, totalResult.value)
    setTimeout(()=>{
      const $table = tableRef.value
      if ($table) {
        $table.print({
          sheetName: '打印消费明细',
          // 打印指定列
          columns: [
            { field: '卡号' },
            { field: '日期' },
            { field: '油品名' },
            { field: '油品号' },
            { field: '车牌号' },
            { field: '数量' },
            { field: '单价金额' },
            { field: '结算金额' },
          ],
          // 打印之前拼接自定义模板
          beforePrintMethod: ({ content }) => {
            // 打印之前，返回自定义的 html 内容
            return content
          }
        })
      }
    }, 1500)
  } else {
    if (totalResult1.value > 3000) {
      ElMessage.warning('由于性能原因，不支持超过3000条的数据打印, 请导出为文件后再打印!')
      return false
    }
    printLoading.value = true
    handlePageChange(1, totalResult1.value)
    setTimeout(()=>{
      const $table = tableRef.value
      if ($table) {
        $table.print({
          sheetName: '打印充值明细',
          // 打印指定列
          columns: [
            { field: '卡号' },
            { field: '名称' },
            { field: '充值时间' },
            { field: '充值金额' },
            { field: '支付类型' },
          ],
          // 打印之前拼接自定义模板
          beforePrintMethod: ({ content }) => {
            // 打印之前，返回自定义的 html 内容
            return content
          }
        })
      }
    }, 1500)
  }
  setTimeout(()=>{
    if (activeName.value === '消费明细') {
      printLoading.value = false
      handlePageChange(print.value.currentPage ? print.value.currentPage : 1, print.value.pageSize ? print.value.pageSize : 10)
    } else {
      printLoading.value = false
      handlePageChange(print1.value.currentPage ? print1.value.currentPage : 1, print1.value.pageSize ? print1.value.pageSize : 10)
    }
  }, 2000)
}
// 导出
function onExport() {
  loading.value = true
  const data = {
    startTime: date.value[0],
    endTime: date.value[1],
    station: station.value
  }
  const config = {
                responseType: 'blob', //这个一定要设置，否则会出现文件下载后打不开的情况
                timeout: 180000
            }
    if (activeName.value === '消费明细') {
      http.post('/client/consumeDetailExport', data, config).then(res => {
      const blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = '客户消费明细.xls' // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
        ElMessage.success('导出成功'); 
        loading.value = false
      }).catch(error => {
        loading.value = false
        ElMessage.error(error)
      })
    } else {
      http.post('/client/rechangeRecordExport', data, config).then(res => {
      const blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = '客户充值明细.xls' // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
        ElMessage.success('导出成功'); 
         loading.value = false
      }).catch(error => {
        loading.value = false
        ElMessage.error(error)
      })
    }
}
function getData(val) {
  if (activeName.value === '消费明细') {
    print.value.currentPage = val.currentPage
    print.value.pageSize = val.pageSize
    handlePageChange(val.currentPage, val.pageSize)
  }
  else {
    print1.value.currentPage = val.currentPage
    print1.value.pageSize = val.pageSize
    handlePageChange(val.currentPage, val.pageSize)
  }
}
function handlePageChange(currentPage, pageSize) {
  if (activeName.value === '消费明细') {
    queryForm.value.currentPage = currentPage;
    queryForm.value.pageSize = pageSize;
    const start = (currentPage - 1) * queryForm.value.pageSize;
    const end = start + queryForm.value.pageSize;
    客户消费明细List.value = 客户消费明细全部数据List.value.slice(start, end);
  } 
  else {
    queryForm1.value.currentPage = currentPage;
    queryForm1.value.pageSize = pageSize;
    const start = (currentPage - 1) * queryForm1.value.pageSize;
    const end = start + queryForm1.value.pageSize;
    客户充值明细List.value = 客户充值明细全部数据List.value.slice(start, end);
  }
}


onMounted(() =>{
  getQueryStation()
  const endDate = moment(); // 结束日期为今天
  const startDate = moment().subtract(2, 'days'); // 开始日期为今天往前推两天
  date.value = [startDate.format('YYYY-MM-DD HH:mm:ss'), endDate.format('YYYY-MM-DD HH:mm:ss')];
  queryList()
})
</script>


<style lang="scss">
  .data_from{
    display: flex;
    .bold{
      font-weight: bold;
      padding-right: 5px;
    }
  }
//   /* 隐藏打印图标 */
.is--circle{
  display: none !important;
}
</style>
